package com.situ.study.day10;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularDemo {

    public static void main1(String[] args) {
        String[] array = {"2019 5013 08", "2019-5013-08", "2019501308"};
        String regex = "(\\d{4})[\\-\\s]?(\\d{4})[\\-\\s]?(\\d{2})";
        Pattern pattern = Pattern.compile(regex);
        for (String string : array) {
            Matcher matcher = pattern.matcher(string);
            if (matcher.find()) {
                //group(0)代表匹配的整个字符串
                //System.out.println(matcher.group(0));
                System.out.println(matcher.group(1) + "-" + matcher.group(2) + "-" + matcher.group(3));
            }
        }
    }

    public static void main(String[] args) {
        String str = "We live at 3234058911296670,not at 0589323411296670.32340589112966703234058911296670";
        List<Integer> positions = findFourConor(str);
        System.out.println(positions);
    }

    static List<Integer> findFourConor(String message) {
        String[] fourCorner = {"3234", "0589", "1129", "6670"};
        List<String> list = Arrays.asList(fourCorner);
        //存放找到位置的集合
        List<Integer> positionList = new ArrayList<>();
        String regex = "\\d{16}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(message);
        int fromIndex = 0;
        while (matcher.find()) {// find找到一个匹配的后会继续往后找后面匹配的
            String str = matcher.group();
            System.out.println(str);
            //3234058911296670
            //0589323411296670
            boolean allMatch = true;
            for (int i = 0; i < str.length(); i += 4) {
                String temp = str.substring(i, i + 4);
                if (!list.contains(temp)) {
                    allMatch = false;
                    break;
                }
            }

            if (allMatch) {
                int position = message.indexOf(str, fromIndex);
                fromIndex = position + str.length();
                positionList.add(position);
            }
        }

        return positionList;
    }

    @Test
    public void testReplace() {
        //public String replaceAll(String regex,String replacement)
        //使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
        // 数字变成：#NUMBER#
        String regex = "\\d+";
        String string = "ehrifdi3456dfhdfhoDSf223dffhfd34hi";
        String result = string.replaceAll(regex, "#NUMBER#");
        System.out.println(result);
    }
}
